"""
Case Type   : 数据库系统
Case Name   : 使用jdbc查询返回结果类型为oid的数据
Create At   : 2022/10/25
Owner       : opentestcase023
Description :
    1.传输java文件并修改参数
    2.编译java文件
    3.运行java预编译代码
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.清理环境
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class JdbcTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.com = Common()
        self.constant = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.pri_root = Node(node='PrimaryRoot')
        self.target_path = os.path.join(os.path.dirname(macro.DB_SCRIPT_PATH),
                                        "JDBC_test")
        self.java_name = "jdbc_set_get_object_case0024"

    def test_set_object(self):
        step_txt = '-----step1:传输java文件并修改参数; expect:成功-----'
        self.log.info(step_txt)
        self.com.scp_file(self.pri_root,
                          f"{self.java_name}.java", self.target_path)
        self.pri_root.scp_put(macro.JDBC_PATH,
                              f"{self.target_path}/postgresql.jar")

        step_txt = '-----step2:编译java文件; expect:编译成功-----'
        self.log.info(step_txt)
        cmd = f"javac -encoding utf-8 -cp " \
            f"{os.path.join(self.target_path, 'postgresql.jar')} " \
            f"{os.path.join(self.target_path, f'{self.java_name}.java')}"
        self.log.info(cmd)
        result = self.com.get_sh_result(self.pri_root, cmd)
        self.assertEqual('', result, "执行失败" + step_txt)

        step_txt = '-----step3:运行java预编译代码; expect:成功-----'
        self.log.info(step_txt)
        url_host_port = f"{self.pri_dbuser.db_host}:{self.pri_dbuser.db_port}"
        cmd = f" java -cp {os.path.join(self.target_path, 'postgresql.jar')}" \
            f":{self.target_path} " \
            f"{self.java_name} {url_host_port} {self.pri_dbuser.db_name} " \
            f"{self.pri_dbuser.db_user} {self.pri_dbuser.db_password}"
        self.log.info(cmd)
        res = self.com.get_sh_result(self.pri_root, cmd)
        self.assertIn(self.pri_dbuser.db_name, res, 'java执行失败')

    def tearDown(self):
        step_txt = '-----step4:清理环境; expect:成功-----'
        self.log.info(step_txt)
        cmd = f'rm -rf {self.target_path};' \
              f'if [ -d {self.target_path} ]; ' \
              f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(cmd)
        del_res = self.com.get_sh_result(self.pri_root, cmd)
        self.assertIn('not exists', del_res, '文件清理失败')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
